using FineCollection.Intf;




namespace FineCollection.Immutable
{
    /// <summary>
    /// Prime numbers. Helps to select a prime number for a hash table.
    /// Interval: 17 .. 199999.
    /// </summary>
    public static class PrimeNumbers
    {
        private static readonly int[] PrimeNumbersForHashArray =
            {17, 53, 163, 499, 1499, 4507, 9001, 18013, 25411, 35831, 
             50503, 70001, 85009, 100003, 125003, 150001, 175003, 199999};


        /// <summary>
        /// Contains the set of prime numbers choosed for hash tables.
        /// </summary>
        public static readonly RRandomSet<int> PrimeHumbersForHash =
            new ImmSortSet<int>(PrimeNumbersForHashArray, 
                                PrimeNumbersForHashArray.Length,
                                true);

        /// <summary>
        /// Selects the prime number from the <see cref="PrimeHumbersForHash"/>
        /// that is the neares to the specified one.
        /// </summary>
        /// <param name="x">specified number for select the nearest prime number.</param>
        /// <returns>selected prime number.</returns>
        public static int SelectRingPowerFor (int x)
        {
            bool found;
            int nearestIndex;

            PrimeHumbersForHash.Find(x, out found, out nearestIndex);

            if (found)
                return x;

            if (nearestIndex == PrimeHumbersForHash.FirstIndex)
                return PrimeHumbersForHash.First;

            int prime1 = PrimeHumbersForHash[nearestIndex - 1],
                prime2 = PrimeHumbersForHash[nearestIndex];
            int delta1 = x = prime1,
                delta2 = prime2 - x;

            return delta1 <= delta2 ? prime1 : prime2;
        }

    }

}